<!-- 注册确认用户协议和隐私 -->
<script lang="ts" setup>
import { Form } from '@varlet/ui'
import { nextTick, ref } from 'vue'

// 定义props
const props = defineProps<{
    modelValue: boolean,
    content?: string,
    rules?: Array<(v: string) => any>
}>()

// 定义外部事件
const emit = defineEmits(['update:modelValue'])

const validateTrigger = ['onToggle'];

// 绑定form
const { useForm, useValidation } = Form
const { errorMessage, validateWithTrigger: _validateWithTrigger, validate: _validate, resetValidation } = useValidation()
const { bindForm, form } = useForm()

const validate = () => _validate(props.rules, props.modelValue)

function reset() {
    emit('update:modelValue', false)
    resetValidation()
}

function validateWithTrigger(trigger: string) {
    nextTick(() => {
        const { rules, modelValue } = props
        _validateWithTrigger(validateTrigger, trigger, rules, modelValue)
    })
}

function handleClick() {
    if (
        form?.readonly.value ||
        form?.disabled.value
    ) {
        return
    }

    emit('update:modelValue', !props.modelValue)
    validateWithTrigger('onToggle')
}

const apis = {
    reset,
    validate,
    resetValidation
}

defineExpose(apis)
bindForm?.(apis)
</script>

<template>
    <div class="form-agreement-box" @click="handleClick">
        <div class="agreement">
            <VarIcon :class="{ agreeicon: true, checked: modelValue }" name="checkbox-marked-circle" :transition="250" />
            <div class="agreement-content">
                <span v-if="!$slots.default">{{ content }}</span>
                <slot></slot>
            </div>
        </div>
        <VarFormDetails :error-message="errorMessage" />
    </div>
</template>

<style lang="scss" scoped>
.form-agreement-box {
    cursor: pointer;

    .agreement {
        display: flex;
        align-items: flex-start;
        color: $text-sub;
        line-height: 40px;

        .agreeicon {
            margin-top: 5px;
            margin-right: 20px;
            font-size: 40px;

            &.checked {
                color: $primary;
            }
        }

        .agreement-content {
            // font-size: 24px;
            color: $text-sub;
        }
    }
}
</style>